/*
 *
 */

package com.hlingsoft.kkh.action.v20;

import com.hlingsoft.kkh.action.BaseAction;

import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.Image;

import com.hlingsoft.kkh.entity.vo.EventsVo1;
import com.hlingsoft.kkh.entity.vo.StartsVo;
import com.hlingsoft.kkh.util.Common;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.List;


/**
 * 职位
 *
 * @author Herbert
 */
@Controller
@RequestMapping("/v20/extension")

public class ExtensionAction_V20 extends BaseAction {


    private static final int rows = 10;


    /**
     * 交友附近
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param pageNum
     * @param request
     * @return
     */
    @RequestMapping(value = "/nearby.json")
    @ResponseBody
    public Map<String, Object> nearby(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "latitude") double latitude,
            @RequestParam(value = "longitude") double longitude,
            @RequestParam(value = "gender") Integer gender,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<StartsVo> startsVoList = new ArrayList<StartsVo>();
            List<AppUser> userList = userDao.getUserByGender(gender, 0, 100);
            for (AppUser user : userList) {
                if (user.getId() != userId) {
                    StartsVo startsVo = new StartsVo();
                    //用户与我的距离
                    if (focusDao.getFocus(userId, user.getId()) == null) {
                        user.setIsFocus(0);
                    } else {
                        user.setIsFocus(1);
                        if (focusDao.getFocus(user.getId(), userId) != null) {
                            user.setIsFocus(2);
                        }
                    }
                    user.setFansCount(focusDao.getFansByIdCount(user.getId()));
                    user.setDistance(Common.getDistance(longitude, latitude, user.getLongitude(), user.getLatitude()));   //用户离我的距离
                    startsVo.setAppUser(user);
                    startsVo.setNewestEvents(eventsDao.getNewestEventsByUserId(user.getId()));

                    startsVoList.add(startsVo);
                }
            }
            Collections.sort(startsVoList, new Comparator<StartsVo>() {
                @Override
                public int compare(StartsVo o1, StartsVo o2) {
                    return o1.getAppUser().getDistance().compareTo(o2.getAppUser().getDistance());
                }
            });

            startsVoList = Common.fenYe3(startsVoList, (pageNum - 1) * rows, rows);

            resultMap.put("startsVoList", startsVoList);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 交友推荐
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param pageNum
     * @param request
     * @return
     */
    @RequestMapping(value = "/recommend.json")
    @ResponseBody
    public Map<String, Object> recommend(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "latitude") double latitude,
            @RequestParam(value = "longitude") double longitude,
            @RequestParam(value = "gender") int gender,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<AppUser> interestList = new ArrayList<AppUser>();
            List<StartsVo> startsVoList = new ArrayList<StartsVo>();
            List<AppUser> userList = new ArrayList<AppUser>();
            List<AppUser> randomList = new ArrayList<AppUser>();

            //达人
            List<AppUser> hotList = userDao.getHostList(gender, 0, 10);

            //兴趣相同的人
            AppUser my = userDao.getUserById(userId);
            if (my != null) {
                String interestIds = my.getInterestIds();
                List<String> interestIdList = Common.strToList(interestIds);
                for (String interestId : interestIdList) {
                    if (userDao.getSameInterest(gender, interestId, 0, 5).size() != 0) {
                        interestList.addAll(userDao.getSameInterest(gender, interestId, 0, 5));
                    }
                }
            }

            //随机10个用户
            List<Integer> ids = userDao.getAllIds(gender);
            if (ids.size() > 1) {
                List<Integer> idList = Common.random(ids);
                if (idList.size() < 10) {
                    for (int i = 0; i < idList.size(); i++) {
                        randomList.add(userDao.getUserById(idList.get(i)));
                    }
                } else {
                    for (int i = 0; i < 10; i++) {
                        randomList.add(userDao.getUserById(idList.get(i)));
                    }

                }
            } else if (ids.size() == 1) {
                randomList.add(userDao.getUserById(ids.get(0)));
            }

            userList.addAll(hotList);
            userList.addAll(interestList);
            userList.addAll(randomList);


            for (AppUser user : userList) {
                if (user.getId() != userId) {
                    StartsVo startsVo = new StartsVo();
                    //用户与我的关注关系
                    if (focusDao.getFocus(userId, user.getId()) == null) {
                        user.setIsFocus(0);
                    } else {
                        user.setIsFocus(1);
                        if (focusDao.getFocus(user.getId(), userId) != null) {
                            user.setIsFocus(2);
                        }
                    }
                    user.setFansCount(focusDao.getFansByIdCount(user.getId()));
                    user.setDistance(Common.getDistance(longitude, latitude, user.getLongitude(), user.getLatitude()));   //用户离我的距离
                    startsVo.setAppUser(user);
                    startsVo.setNewestEvents(eventsDao.getNewestEventsByUserId(user.getId()));

                    startsVoList.add(startsVo);
                }
            }
            Set<StartsVo> ts = new HashSet<StartsVo>();
            ts.addAll(startsVoList);

            List<StartsVo> resultList = new ArrayList<StartsVo>();
            resultList.addAll(ts);
            resultList = Common.fenYe3(resultList, (pageNum - 1) * rows, rows);

            resultMap.put("startsVoList", resultList);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * Ta在现场
     *
     * @param userId
     * @param eventsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/inEventsList")
    @ResponseBody
    public Map<String, Object> inEventsList(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventsId") long eventsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Events events = eventsDao.getEventsById(eventsId);

            List<StartsVo> startsVoList = new ArrayList<StartsVo>();
            List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByEventId(eventsId);
            List<AppUser> userList = new ArrayList<AppUser>();
            for (EventComments eventComments : eventCommentsList) {
                AppUser user = userDao.getUserById(eventComments.getAppUserId());
                userList.add(user);
                List<Reply> replyList = replyDao.getAllReplyByEventCommentsId(eventComments.getId());
                for (Reply reply : replyList) {
                    AppUser replyUser = userDao.getUserById(reply.getMyId());
                    userList.add(replyUser);
                }
            }

            for (AppUser user : userList) {
                Double distance = (Common.getDistance(user.getLongitude(), user.getLatitude(), events.getLongitude(), events.getLatitude())) / 1000;
                user.setDistance(distance);
                if (distance <= 2) {
                    //粉丝数
                    long fansCount = focusDao.getFansByIdCount(user.getId());
                    user.setFansCount(fansCount);

                    //关注关系
                    if (focusDao.getFocus(userId, user.getId()) == null) {
                        user.setIsFocus(0);
                    } else {
                        user.setIsFocus(1);
                        if (focusDao.getFocus(user.getId(), userId) != null) {
                            user.setIsFocus(2);
                        }
                    }

                    Events newestEvents = eventsDao.getNewestEventsByUserId(user.getId());
                    StartsVo startsVo = new StartsVo();
                    startsVo.setAppUser(user);
                    startsVo.setNewestEvents(newestEvents);
                    startsVoList.add(startsVo);
                }
            }

            Set<StartsVo> ts = new HashSet<StartsVo>();
            ts.addAll(startsVoList);

            resultMap.put("startsVoList", ts);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 发现好友
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping(value = "/findFriends.json")
    @ResponseBody
    public Map<String, Object> interested(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventsId") long eventsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser my = userDao.getUserById(userId);
            List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByEventId(eventsId);
            List<AppUser> appUserList = new ArrayList<AppUser>();


            for (EventComments eventComments : eventCommentsList) {

                AppUser user = userDao.getUserById(eventComments.getAppUserId());
                if (user != null) {
                    appUserList.add(user);
                }

                List<Reply> replyList = replyDao.getAllReplyByEventCommentsId(eventComments.getId());
                for (Reply reply : replyList) {
                    AppUser replyUser = userDao.getUserById(reply.getMyId());
                    if (replyUser != null) {
                        appUserList.add(replyUser);
                    }
                }
            }
            for (AppUser appUser : appUserList) {
                if (focusDao.getFocus(userId, appUser.getId()) == null) {
                    appUser.setIsFocus(0);
                } else {
                    appUser.setIsFocus(1);
                    if (focusDao.getFocus(appUser.getId(), userId) == null) {
                        appUser.setIsFocus(2);
                    }
                }
                Double distance = Common.getDistance(my.getLongitude(), my.getLongitude(), appUser.getLongitude(), appUser.getLatitude());
                if (distance > 1) {
                    appUser.setIsIn("场外游客");
                } else {
                    appUser.setIsIn("Ta在现场");
                }
            }

            Set<AppUser> ts = new HashSet<AppUser>();
            ts.addAll(appUserList);
            resultMap.put("appUserList", ts);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 邀请好友
     *
     * @param myId
     * @param userIds
     * @param eventsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/invite.json")
    @ResponseBody
    public Map<String, Object> invite(
            @RequestParam(value = "myId") Integer myId,
            @RequestParam(value = "userIds", required = false) String userIds,
            @RequestParam(value = "eventsId") long eventsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (userIds != null) {
                List<Integer> userIdList = Common.strToIntegerList(userIds);
                for (Integer userId : userIdList) {
                    Date now = new Date();
                    Notification notification = new Notification();
                    notification.setEventsId(eventsId);
                    notification.setMyId(myId);
                    AppUser myUser = userDao.getUserById(myId);

                    notification.setMyName(myUser.getName());
                    notification.setMyImageHead(myUser.getHeadImage());
                    notification.setToId(userId.longValue());
                    AppUser toUser = userDao.getUserById(userId.longValue());
                    notification.setToName(toUser.getName());
                    //跟帖的第一张图片
                    EventComments firstEventComments = eventCommentsDao.getFirstEventComments(eventsId);
                    List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                    notification.setToImage(imageList.get(0).getPath());
                    notification.setContent("我们这里好好玩，快来加入吧");
                    notification.setType(6);
                    notification.setTarget(2);
                    notification.setCreateTime(now);
                    notification.setUpdateTime(now);
                    notificationDao.addNotification(notification);

                    MessageStatus messageStatus = new MessageStatus();
                    messageStatus.setAppUserId(userId);
                    messageStatus.setType(2);
                    messageStatus.setMessageId(notification.getId());
                    messageStatusDao.addMessageStatus(messageStatus);
                }
            }
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 周边现场
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param pageNum
     * @param request
     * @return
     */
    @RequestMapping(value = "/rim.json")
    @ResponseBody
    public Map<String, Object> rim(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<EventsVo1> eventsVo1List = new ArrayList<EventsVo1>();
            List<Events> eventsList = new ArrayList<Events>();

            List<Events> pushList = eventsDao.getByPushName("周边", 0, 10);
            List<Events> rimList = eventsDao.getNearlyEvents(userId, latitude, longitude, 0, 10);

            eventsList.addAll(pushList);
            eventsList.addAll(rimList);




            eventsList = Common.fenYe(eventsList, (pageNum - 1) * rows, rows);

            for (Events events : eventsList) {
                List<AppUser> collectUserList = new ArrayList<AppUser>();

                EventsVo1 eventsVo1 = new EventsVo1();
                //活动id
                eventsVo1.setId(events.getId());
                //活动名
                eventsVo1.setName(events.getName());
                //活动图片
                EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                eventsVo1.setImageList(imageList);
                eventsVo1.setEventCommentsId(firstEventComments.getId());
                //活动发布人信息
                eventsVo1.setAppUserId(events.getAppUserId());
                eventsVo1.setAppUser(userDao.getUserById(events.getAppUserId()));
                //活动描述
                eventsVo1.setDescription(events.getDescription());

                //评论
                List<Reply> replyList = replyDao.getReplyByEventCommentsId(firstEventComments.getId(), 0, 2);
                for (Reply reply:replyList){
                    AppUser my = userDao.getUserById(reply.getMyId());
                    if(my!=null){
                        reply.setMyHeadImage(my.getHeadImage());
                    }
                }
                Collections.sort(replyList, new Comparator<Reply>() {
                    @Override
                    public int compare(Reply o1, Reply o2) {
                        return o1.getCreateTime().compareTo(o2.getCreateTime());
                    }
                });
                eventsVo1.setReplyList(replyList);

                //经纬度
                eventsVo1.setLatitude(events.getLatitude());
                eventsVo1.setLongitude(events.getLongitude());

                //创建时间
                eventsVo1.setCreateAddress(events.getCreateAddress());
                eventsVo1.setCreateTime(events.getCreateTime());
                eventsVo1.setUpdateTime(events.getUpdateTime());

                //距离
                Double des = Common.getDistance(longitude, latitude, events.getLongitude(), events.getLatitude());
                eventsVo1.setDistance(des);


                //收藏人
                List<Collect> collectList = collectDao.getByEventsId(events.getId(), 0, 10);
                for (Collect collect : collectList) {
                    AppUser appUser = userDao.getUserById(collect.getAppUserId());
                    if (appUser != null) {
                        collectUserList.add(appUser);
                    }
                }
                eventsVo1.setCollectUserList(collectUserList);
                eventsVo1.setCollectCount(collectDao.getByEventsIdCount(events.getId()));

                //是否能收藏
                if (userId != 0) {
                    if (collectDao.getByIds(userId, events.getId()) == null) {
                        eventsVo1.setIsCollect(0);
                    } else {
                        eventsVo1.setIsCollect(1);
                    }
                } else {
                    eventsVo1.setIsCollect(0);
                }

                eventsVo1List.add(eventsVo1);
            }

            resultMap.put("eventsVo1List", eventsVo1List);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 热门
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param pageNum
     * @param request
     * @return
     */
    @RequestMapping(value = "/hot.json")
    @ResponseBody
    public Map<String, Object> hot(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<EventsVo1> eventsVo1List = new ArrayList<EventsVo1>();
            List<Events> eventsList = new ArrayList<Events>();

            List<Events> pushList = eventsDao.getByPushName("热门", 0, 10);


            eventsList.addAll(pushList);

            eventsList = Common.fenYe(eventsList, (pageNum - 1) * rows, rows);

            for (Events events : eventsList) {
                List<AppUser> collectUserList = new ArrayList<AppUser>();

                EventsVo1 eventsVo1 = new EventsVo1();
                //活动id
                eventsVo1.setId(events.getId());
                //活动名
                eventsVo1.setName(events.getName());
                //活动图片
                EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                eventsVo1.setImageList(imageList);
                eventsVo1.setEventCommentsId(firstEventComments.getId());
                //活动发布人信息
                eventsVo1.setAppUserId(events.getAppUserId());
                eventsVo1.setAppUser(userDao.getUserById(events.getAppUserId()));
                //活动描述
                eventsVo1.setDescription(events.getDescription());

                //评论
                List<Reply> replyList = replyDao.getReplyByEventCommentsId(firstEventComments.getId(), 0, 2);
                for (Reply reply:replyList){
                    AppUser my = userDao.getUserById(reply.getMyId());
                    if(my!=null){
                        reply.setMyHeadImage(my.getHeadImage());
                    }
                }
                Collections.sort(replyList, new Comparator<Reply>() {
                    @Override
                    public int compare(Reply o1, Reply o2) {
                        return o1.getCreateTime().compareTo(o2.getCreateTime());
                    }
                });
                eventsVo1.setReplyList(replyList);

                //经纬度
                eventsVo1.setLatitude(events.getLatitude());
                eventsVo1.setLongitude(events.getLongitude());

                //创建时间
                eventsVo1.setCreateAddress(events.getCreateAddress());
                eventsVo1.setCreateTime(events.getCreateTime());
                eventsVo1.setUpdateTime(events.getUpdateTime());


                //收藏人
                List<Collect> collectList = collectDao.getByEventsId(events.getId(), 0, 10);
                for (Collect collect : collectList) {
                    AppUser appUser = userDao.getUserById(collect.getAppUserId());
                    if (appUser != null) {
                        collectUserList.add(appUser);
                    }
                }
                eventsVo1.setCollectUserList(collectUserList);
                eventsVo1.setCollectCount(collectDao.getByEventsIdCount(events.getId()));

                //是否能收藏
                if (userId != 0) {
                    if (collectDao.getByIds(userId, events.getId()) == null) {
                        eventsVo1.setIsCollect(0);
                    } else {
                        eventsVo1.setIsCollect(1);
                    }
                } else {
                    eventsVo1.setIsCollect(0);
                }

                eventsVo1List.add(eventsVo1);
            }

            resultMap.put("eventsVo1List", eventsVo1List);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


}
